Gatherer = Gatherer or class({})

function Gatherer:Init()
	CustomGameEventManager:RegisterListener("check_tree_click", function(id, ...) Dynamic_Wrap(Gatherer, "CheckTreeClick")(Gatherer, ...) end)
end

function Gatherer:CheckTreeClick(events)
	local playerId = events.PlayerID

	local unit = EntIndexToHScript(events.unitIndex)
	if unit == nil or not unit:IsAlive() or unit.GetParentEntity == nil then
		return
	end
	unit = unit:GetParentEntity()

	local position = GetGroundPosition(Vector(events.position["0"], events.position["1"], events.position["2"]), nil)

	unit:GetUnit().clickTree = true
	GameRules:GetGameModeEntity():SetContextThink(DoUniqueString("Check"),
		function()
			if unit:GetUnit().clickTree == true then
				local trees = GridNav:GetAllTreesAroundPoint(position, 0, true)
				table.sort(trees, function(a,b) return (a:GetAbsOrigin()-position):Length2D() < (b:GetAbsOrigin()-position):Length2D() end)
				if #trees > 0 then
					Gatherer:OnTreeClick(unit, trees[1]:GetParentEntity())

					if unit.clickTreeParticleId ~= nil then
						ParticleManager:DestroyParticle(unit.clickTreeParticleId, true)
					end
					unit.clickTreeParticleId = ParticleManager:CreateParticleForPlayer("particles/ui_mouseactions/clicked_unit_select.vpcf", PATTACH_WORLDORIGIN, unit:GetUnit(), PlayerResource:GetPlayer(playerId))
					ParticleManager:SetParticleControl(unit.clickTreeParticleId, 0, trees[1]:GetAbsOrigin())
					ParticleManager:SetParticleControl(unit.clickTreeParticleId, 1, Vector(255,255,255))
					ParticleManager:SetParticleControl(unit.clickTreeParticleId, 2, Vector(96,0,0))
				else
					ExecuteOrderFromTable(
						{
							UnitIndex = unit:GetUnit():entindex(),
							OrderType = DOTA_UNIT_ORDER_MOVE_TO_POSITION,
							Position = position,
							AbilityIndex = 0,
							Queue = 0,
						}
					)
					local particleId = ParticleManager:CreateParticleForPlayer("particles/ui_mouseactions/clicked_basemove.vpcf", PATTACH_WORLDORIGIN, unit:GetUnit(), PlayerResource:GetPlayer(playerId))
					ParticleManager:SetParticleControl(particleId, 0, position)
					ParticleManager:SetParticleControl(particleId, 1, Vector(0, 255, 0))
					ParticleManager:ReleaseParticleIndex(particleId)
				end
			end
			unit:GetUnit().clickTree = nil
			return
		end
	, 0)
end

function Gatherer:OnTreeClick(unit, tree)
	ExecuteOrderFromTable(
		{
			UnitIndex = unit:GetUnit():entindex(),
			OrderType = DOTA_UNIT_ORDER_CAST_TARGET_TREE,
			TargetIndex = tree:GetTreeId(),
			AbilityIndex = unit:GetUnit():FindAbilityByName("cut_tree"):entindex(),
			Queue = 0,
		}
	)
end